// src/router/guard.js
import router from '@/router'

// 需要登录才能访问的页面路径
const protectedRoutes = [
  '/profile',
  '/cart',
  '/orders',
  '/order'
]

router.beforeEach((to, from, next) => {
  const requiresAuth = protectedRoutes.some(route => to.path.startsWith(route))
  
  if (requiresAuth) {
    const userInfo = localStorage.getItem('userInfo')
    
    if (!userInfo) {
      window.dispatchEvent(new CustomEvent('need-login', {
        detail: { path: to.fullPath }
      }))
      return
    }
    
    try {
      const user = JSON.parse(userInfo)
      if (!user.username) {
        window.dispatchEvent(new CustomEvent('need-login', {
          detail: { path: to.fullPath }
        }))
        return
      }
    } catch (e) {
      window.dispatchEvent(new CustomEvent('need-login', {
        detail: { path: to.fullPath }
      }))
      return
    }
  }
  
  next()
})